package MyGui;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
import java.lang.*;

import DistSys.*;
import Element.*;
import Element.Geom.*;
//import Element.PwrPkg.*;

/**
 * The class <code>SelectVoltageLevelDlg</code> implements a form to select
 * voltage levels within the system.
 *
 * @author  Christian Krane, ABB Inc.
 * @version 1.0, 03/13/02
 */

public class SelectVoltageLevelDlg extends MyDlgFrame implements ActionListener {
  private JTextField  tfSelectedVoltageLevel;
  private JList       lstAllVoltageLevels;
  private JButton     btnSelect, btnAddToSelection;
  private Vector      allVoltageLevels; // for correct format and order
  private int[]       selectedVoltageLevels;  // stores the indices of the selected voltage levels in allVoltageLevels

  public SelectVoltageLevelDlg(MainFrame parent, String title) {
      super(parent, title);

      tfSelectedVoltageLevel = new JTextField(6);
      btnSelect= new JButton("Select");
      btnAddToSelection = new JButton("Add to Selection");

      createVoltageLevelList ();
      lstAllVoltageLevels = new JList(allVoltageLevels) ;
      lstAllVoltageLevels.setSelectionMode( DefaultListSelectionModel.SINGLE_SELECTION);

      tfSelectedVoltageLevel.getDocument().addDocumentListener(dlTFSelectedVoltageLevel);

      JScrollPane scrollPaneForAllZones = new JScrollPane(lstAllVoltageLevels);
          // Or in two steps:
          //JScrollPane scrollPane = new JScrollPane();
          //scrollPane.getViewport().setView(dataList);
      scrollPaneForAllZones.setPreferredSize( new Dimension(100,75));

      Container pane= this.getContentPane();
      GridBagConstraints c = new GridBagConstraints();
      pane.setLayout( gridBagLayout );

      c.insets = new Insets(3,3,3,3);
      c.fill = GridBagConstraints.BOTH;

      c.gridy=0;
        c.gridx=0;c.weightx=100; pane.add(tfSelectedVoltageLevel,c);
        c.gridx=1;c.weightx=0; pane.add(new JLabel("Voltage Level (kV)"),c);


      c.gridy=1;
        c.gridheight=2;
        c.gridx=0;c.weightx=100; c.weighty=100; pane.add(scrollPaneForAllZones,c);
        c.gridheight=1;
        c.gridx=1;c.weightx=0; c.weighty=0; pane.add(btnSelect,c);

      c.gridy=2;
      c.anchor=GridBagConstraints.NORTH; c.fill=GridBagConstraints.HORIZONTAL;
      c.gridx=1;c.weightx=0;  pane.add(btnAddToSelection,c);

      btnSelect.addActionListener(this);
      btnAddToSelection.addActionListener(this);

      this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
      this.setSize(250,140);
      this.setLocation(500,500);

      getRootPane().setDefaultButton(btnSelect);

      addWindowListener(new WindowAdapter() {
      public void windowActivated(WindowEvent evt) {
        updateContent();
      }
    });
   } // end of constructor

  private void createVoltageLevelList () {
    // graphical output for VoltageLevelList...set output format
    NumberFormat doubleFormat = NumberFormat.getNumberInstance();
    doubleFormat.setMaximumFractionDigits(2);
    doubleFormat.setMinimumFractionDigits(0);
    // initialize new vector with strings (VoltageLevels) in descending order
    // or set the new size for the vector if this method had been called before
    if (allVoltageLevels == null)
        allVoltageLevels = new Vector (Sys.voltageLevels.size());
    else {
        allVoltageLevels.clear();
        allVoltageLevels.ensureCapacity(Sys.voltageLevels.size());
    }
    int j=Sys.voltageLevels.size();
    for (int i=0 ; i<j ; i++) {
      double d= ((Double)Sys.voltageLevels.get(j-1-i)).doubleValue();
      allVoltageLevels.addElement(doubleFormat.format(d)+" kV");
    }// end of for
  } // end of createVoltageList ()

  public void updateContent() {
      Sys.assignVoltageLevelToAllElements(true); // block warning message
      createVoltageLevelList();
      lstAllVoltageLevels.setListData(allVoltageLevels); // the changed vector "allVoltageLevels" is updated in the list
      // reset list of selected voltage levels and ajust the size if necessary
      selectedVoltageLevels= new int[Sys.voltageLevels.size()];
      for (int i=0;i<Sys.voltageLevels.size(); i++) { selectedVoltageLevels [i]= -1;};
      lstAllVoltageLevels.setSelectedIndex(0); //select the first entry in list
  } //end of updateContent ()

  private void selectElements () {
      for (int i=0; i<Sys.voltageLevels.size();i++) {
          if (selectedVoltageLevels [i] < 0) break; //no more voltage levels selected
          int tmp = Sys.voltageLevels.size()-1-selectedVoltageLevels [i];
          double voltageLev =((Double)Sys.voltageLevels.get(tmp)).doubleValue();
           // graphical output for Textfield...set output format
          NumberFormat doubleFormat = NumberFormat.getNumberInstance();
          doubleFormat.setMaximumFractionDigits(2);
          doubleFormat.setMinimumFractionDigits(0);
          //the last selected voltage level is displayed in the text field
          tfSelectedVoltageLevel.setText(doubleFormat.format(voltageLev)+" kV");
          // go through all the elements and select the once with the correct voltage level
          for(int j=0; j<Sys.elemList.size() ; j++) {
              AbsElem elem = (AbsElem) Sys.elemList.elementAt(j);
              //CktLaw ckt= elem.getCktLawObj();
              double difference = Math.abs(voltageLev-elem.getResult(AbsElem.RES_NOMINAL_VOLT) );
              if (difference < Sys.DOUBLE_COMPARE*voltageLev) {
                  // if voltage level are equal...
                  Sys.addElemToSelection(elem);
              }// end of if
          }  // end of for (element loop)
      } // end of for (voltage level loop)
  } //end of selectElements()

  //action listener
  public void actionPerformed(ActionEvent evt){
      Object o = evt.getSource();
      if ( o == this.btnSelect) {
        Sys.clearSelectionAndFocus();
        // initialize selected voltage list with -1
        for (int i=0;i<Sys.voltageLevels.size(); i++) { selectedVoltageLevels [i]= -1;};
        // add element at first place in selected voltage list
        selectedVoltageLevels[0] = lstAllVoltageLevels.getSelectedIndex();
        selectElements ();

      }// end of "if btnSelect is pushed"
      else if (o == this.btnAddToSelection) {
        int i;
        for (i=0;i<Sys.voltageLevels.size(); i++) {
          if (selectedVoltageLevels [i]== -1 ||
          selectedVoltageLevels [i] == lstAllVoltageLevels.getSelectedIndex() ) break;
        };
        // add element at the first vacant place in selected voltage list or at the
        // same place were it had been added earlier (this prevents this list from data overflow)
        selectedVoltageLevels[i] = lstAllVoltageLevels.getSelectedIndex();
        selectElements ();
      } // end of "else if btnAddToSelection is pushed"
      tfSelectedVoltageLevel.requestFocus();
      tfSelectedVoltageLevel.selectAll();
      mainFrame.mainPanel.needRedraw=true;
      mainFrame.mainPanel.repaint();
  } //end of actionPerformed

    DocumentListener dlTFSelectedVoltageLevel = new DocumentListener(){
        public void insertUpdate(DocumentEvent evt){
            selectElemInVoltageLevelList();
        }//end of insertUpdate
        public void removeUpdate(DocumentEvent evt){
            selectElemInVoltageLevelList();
        }//end of removeUpdate
        public void changedUpdate(DocumentEvent evt){
        }//end of changedUpdate
    };// end of DocumentListener

    private void selectElemInVoltageLevelList (){
        for (int i=0 ; i<allVoltageLevels.size() ; i++) {
            String comp=(String)allVoltageLevels.elementAt(i);
            String comp2=tfSelectedVoltageLevel.getText();
            if(comp.startsWith(comp2)) {
                lstAllVoltageLevels.setSelectedIndex(i);
                break;//more than one element cannot be selected
            }
        }//end of for-loop
    }//end of selectElemInVoltageLevelList

}
